<template>
  <!-- PersonAdd 添加 -->
  <PageContainer>
    <view class="container">
      <Header :title="id ? '编辑' : '添加'" />
      <view class="content">
        <view class="title">人员信息</view>
        <BasicsForm
          v-if="info"
          @register="formRegister"
          :btn-group-options="{
            submit: {
              text: '保存',
            },
          }"
          @submit="onSubmit"
        />
      </view>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /**  PersonAdd  添加 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import Header from '@/components/Header/index.vue';
  import BasicsForm from '@/components/Form/BasicsForm.vue';
  import { navigateBack, onLoad } from '@/router';
  import { ref, watch } from 'vue';
  import { type FormActionType, type FormSchema, useForm } from '@/components/Form';
  import { leadingMemberAdd, leadingMemberEdit, leadingMemberInfo } from '@/api/admin/index';
  import { type ILeadingMemberAddData } from '@/api/admin/types';
  import { Toast } from '@/utils';
  import { MemberRoleEnum } from '@/enums/memberRoleEnum';

  const cocId = ref();
  const id = ref();
  let callback: () => void;
  let info = ref();
  onLoad<'PersonAdd'>((op) => {
    cocId.value = op.cocId;
    id.value = op.id;
    callback = op.callback;
    if (id.value) getLeadingMemberInfo();
    else info.value = {};
  });

  const getLeadingMemberInfo = async () => {
    let res = await leadingMemberInfo(id.value);
    info.value = res;
  };

  const schemas: FormSchema[] = [
    {
      field: 'name',
      label: '姓名',
      required: true,
      component: 'Input',
    },
    {
      field: 'socialPosition',
      label: '职务',
      required: true,
      component: 'Input',
    },
    {
      field: 'phone',
      label: '手机号',
      required: true,
      component: 'InputPhone',
    },
    {
      field: 'memberRoleType',
      label: '管理员',
      component: 'Switch',
    },
    {
      field: 'avatar',
      label: '商务照',
      component: 'UploadImg',
      componentProps: {
        isCrop: true,
        cropOptions: {
          width: 640,
          height: 760,
        },
      },
    },
  ];

  const [register, { updateSchema, appendSchemaByField, setFieldsValue, removeSchemaByFiled }] =
    useForm({
      labelAlign: 'left',
      validateTrigger: 'bind',
      schemas,
    });

  function formRegister(instance: FormActionType) {
    register(instance);
    if (id.value) {
      let vals: any = {};
      for (let index = 0; index < schemas.length; index++) {
        const item = schemas[index];
        if (item.field === 'memberRoleType') {
          setFieldsValue({
            memberRoleType: info.value[item.field] === MemberRoleEnum.MANAGER,
          });
        } else {
          vals[item.field] = info.value[item.field];
        }
      }
      setFieldsValue(vals);
    }

    if (info.value.memberRoleType === MemberRoleEnum.PRINCIPAL)
      removeSchemaByFiled('memberRoleType');
  }

  const onSubmit = (data: ILeadingMemberAddData) => {
    let memberRoleType = info.value.memberRoleType;
    if (memberRoleType !== MemberRoleEnum.PRINCIPAL) {
      memberRoleType = data.memberRoleType ? MemberRoleEnum.MANAGER : MemberRoleEnum.MEMBER;
    }
    if (id.value) {
      leadingMemberEdit({ ...data, id: id.value, cocId: cocId.value, memberRoleType }).then(() =>
        success(),
      );
    } else {
      leadingMemberAdd({ ...data, cocId: cocId.value, memberRoleType }).then(() => success());
    }
  };

  const success = () => {
    const duration = 1500;
    Toast({
      title: '保存成功',
      icon: 'success',
      duration,
      mask: true,
      success: () => {
        callback?.();
        navigateBack();
      },
    });
  };
</script>

<style lang="scss" scoped>
  .content {
    .title {
      position: relative;
      height: 100rpx;
      line-height: 100rpx;
      font-size: 32rpx;
      font-weight: bold;
      color: #333333;
      background-color: #fff;
      padding-left: 30rpx;
      z-index: 1;
    }

    .title::after {
      position: absolute;
      content: '';
      width: 112rpx;
      height: 14rpx;
      background: #ffe7b4;
      top: 57rpx;
      left: 30rpx;
      z-index: -1;
    }
  }
</style>
